package cn.iocoder.yudao.module.famous.doctor.service.forum;

import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.famous.doctor.controller.admin.forumRecord.vo.FamForumRecordExportReqVO;
import cn.iocoder.yudao.module.famous.doctor.controller.admin.reply.Enum.ReplyEnum;
import cn.iocoder.yudao.module.famous.doctor.controller.admin.reply.vo.FamReplyExportReqVO;
import cn.iocoder.yudao.module.famous.doctor.dal.dataobject.forumRecord.FamForumRecordDO;
import cn.iocoder.yudao.module.famous.doctor.dal.dataobject.reply.FamReplyDO;
import cn.iocoder.yudao.module.famous.doctor.service.forumRecord.FamForumRecordServiceImpl;
import cn.iocoder.yudao.module.famous.doctor.service.reply.FamReplyServiceImpl;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.dal.dataobject.user.vo.MemberUserParamDO;
import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.famous.doctor.controller.admin.forum.vo.*;
import cn.iocoder.yudao.module.famous.doctor.dal.dataobject.forum.FamForumDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;

import cn.iocoder.yudao.module.famous.doctor.convert.forum.FamForumConvert;
import cn.iocoder.yudao.module.famous.doctor.dal.mysql.forum.FamForumMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.famous.doctor.enums.ErrorCodeConstants.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;

/**
 * 论坛表 Service 实现类
 *
 * @author Test1
 */
@Service
@Validated
@Slf4j
public class FamForumServiceImpl implements FamForumService {

    @Resource
    private FamForumMapper famForumMapper;
    @Resource
    private FamForumRecordServiceImpl famForumRecordService;
    @Resource
    private FamReplyServiceImpl famReplyService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private MemberUserService memberUserService;


    @Override
    public Long createFamForum(FamForumCreateReqVO createReqVO) {
        // 插入
        FamForumDO famForum = FamForumConvert.INSTANCE.convert(createReqVO);
        famForumMapper.insert(famForum);
        // 返回
        return famForum.getId();
    }

    @Override
    public void updateFamForum(FamForumUpdateReqVO updateReqVO) {
        // 校验存在
        validateFamForumExists(updateReqVO.getId());
        // 更新
        FamForumDO updateObj = FamForumConvert.INSTANCE.convert(updateReqVO);
        famForumMapper.updateById(updateObj);
    }

    @Override
    public void deleteFamForum(Long id) {
        // 校验存在
        validateFamForumExists(id);
        // 删除
        famForumMapper.deleteById(id);
    }

    private void validateFamForumExists(Long id) {
        if (famForumMapper.selectById(id) == null) {
            throw exception(FAM_FORUM_NOT_EXISTS);
        }
    }

    @Override
    public FamForumDO getFamForum(Long id) {
        return famForumMapper.selectById(id);
    }

    @Override
    public List<FamForumDO> getFamForumList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return famForumMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<FamForumDO> getFamForumPage(FamForumPageReqVO pageReqVO) {
        return famForumMapper.selectPage(pageReqVO);
    }

    @Override
    public List<FamForumDO> getFamForumList(FamForumExportReqVO exportReqVO) {
        return famForumMapper.selectList(exportReqVO);
    }

    @Override
    public PageResult<FamForumRespTwoVO> getFamForumPageParticulars(FamForumPageReqVO pageVO) {
        PageResult<FamForumRespTwoVO> famForumRespVOPageResult = FamForumConvert.INSTANCE.convertPage2(famForumMapper.selectPageParticulars(pageVO));
        dataProcessing(famForumRespVOPageResult.getList());

        return famForumRespVOPageResult;
    }

    @Override
    public List<FamForumRespTwoVO> getFamForumRandomParticulars(FamForumPageReqVO pageVO) {
        List<FamForumDO> famForumDOS = famForumMapper.selectList(pageVO);
        List<FamForumRespTwoVO> famForumRespTwoVO=FamForumConvert.INSTANCE.convertFamForumRespTwoVO(famForumDOS);
        dataProcessing(famForumRespTwoVO);
        return famForumRespTwoVO;
    }

    public void dataProcessing(List<FamForumRespTwoVO> pageVO) {
        //获取【回复】记录表所有信息
        List<FamReplyDO> famReplyList = famReplyService.getFamReplyList(new FamReplyExportReqVO());

        pageVO.forEach(famForumRespVO -> {
            //查询论坛回复量
            famForumRespVO.setReplyCount(famReplyList.stream().filter(famReplyDO -> famReplyDO.getForumId().equals(famForumRespVO.getId())).count());
            //查询谈论点赞数量
            famForumRespVO.setUpvoteCount(getCollectCount(famForumRespVO.getId(), ReplyEnum.REPLY_UPVOTE));
            //查询该谈论  用户是否收藏量
            famForumRespVO.setIsUpvote(getCollectCount(null, famForumRespVO.getId(), ReplyEnum.REPLY_UPVOTE));
            //查询谈论收藏量
            famForumRespVO.setCollectCount(getCollectCount(famForumRespVO.getId(), ReplyEnum.REPLY_COLLECT));
            //查询该谈论  用户是否收藏量
            famForumRespVO.setIsCollect(getCollectCount(null, famForumRespVO.getId(), ReplyEnum.REPLY_COLLECT));
            MemberUserDO user = memberUserService.getUser(Long.valueOf(famForumRespVO.getCreator()));
            if (user!=null) {
                MemberUserParamDO memberUserParamDO = new MemberUserParamDO();
                BeanUtils.copyProperties(user,memberUserParamDO);
                famForumRespVO.setPublishUserMessage(memberUserParamDO);
            }
        });
    }
    /**
     * 获取论坛 点赞/收藏 数量
     *
     * @param forumId    论谈id标识
     * @param replyState 类型 1点赞 2收藏
     * @return
     */
    public Long getCollectCount(Long forumId, ReplyEnum replyState) {
//        FamForumRecordExportReqVO famForumRecordExportReqVO = new FamForumRecordExportReqVO()
//                .setForumId(forumId)
//                .setState(replyState.getValue());
//        List<FamForumRecordDO> famForumRecordList = famForumRecordService.getFamForumRecordList2(famForumRecordExportReqVO, false);

        String key = "fam_forum_record"+ ":" +replyState.getValue();
        List<FamForumRecordDO>  famForumRecordList = redisTemplate.opsForHash().values(key);
        long count = famForumRecordList.stream()
                .filter(famForumRecordDO ->
                        famForumRecordDO.getForumId() == forumId && famForumRecordDO.getThumbsupId() == null).count();
        return count;
    }

    /**
     * 获取登录用户 点赞/收藏的内容
     *
     * @param thumbsupId   论谈回复id(区分回复途径 空值代表对论坛的回复  有值是对论坛下回复id的回复)
     * @param forumId      论谈id标识
     * @param replyState   类型 1点赞 2收藏
     * @return 1已点赞/收藏 2 未点赞/收藏
     */
    public Long getCollectCount(Long thumbsupId, Long forumId, ReplyEnum replyState) {
//        FamForumRecordExportReqVO famForumRecordExportReqVO = new FamForumRecordExportReqVO()
//                .setForumId(forumId)
//                .setState(replyState.getValue())
//                .setThumbsupId(thumbsupId)
//                ;
//        boolean empty = famForumRecordService.getFamForumRecordList2(famForumRecordExportReqVO, true).isEmpty();

        String key = "fam_forum_record"+ ":" +replyState.getValue();
        String hashkey = getLoginUserId()+"_"+ forumId  +"_"+ thumbsupId;
        Boolean empty = redisTemplate.opsForHash().hasKey(key, hashkey);
        return (long) (!empty == true ? 0 : 1);
    }

}
